package com.ppandroid.wifiap.manager

import android.util.Log
import fi.iki.elonen.NanoHTTPD
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.concurrent.atomic.AtomicInteger

/**
 * HTTP服务器管理器
 */
class HttpServerManager {
    
    private var httpServer: SimpleHttpServer? = null
    private val accessCount = AtomicInteger(0)
    var onAccessCallback: ((Int) -> Unit)? = null
    
    companion object {
        private const val TAG = "HttpServerManager"
        private const val PORT = 8080
    }
    
    /**
     * 启动HTTP服务器
     */
    suspend fun startServer(): Boolean = withContext(Dispatchers.IO) {
        try {
            if (httpServer == null) {
                httpServer = SimpleHttpServer(PORT, accessCount)
            }
            httpServer?.start()
            Log.i(TAG, "HTTP服务器已启动，端口: $PORT")
            true
        } catch (e: Exception) {
            Log.e(TAG, "启动HTTP服务器失败", e)
            false
        }
    }
    
    /**
     * 停止HTTP服务器
     */
    suspend fun stopServer(): Boolean = withContext(Dispatchers.IO) {
        try {
            httpServer?.stop()
            httpServer = null
            Log.i(TAG, "HTTP服务器已停止")
            true
        } catch (e: Exception) {
            Log.e(TAG, "停止HTTP服务器失败", e)
            false
        }
    }
    
    /**
     * 检查服务器是否正在运行
     */
    fun isServerRunning(): Boolean {
        return httpServer?.isAlive == true
    }
    
    /**
     * 获取访问次数
     */
    fun getAccessCount(): Int = accessCount.get()
    
    /**
     * 重置访问次数
     */
    fun resetAccessCount() {
        accessCount.set(0)
    }
    
    /**
     * 获取服务器URL
     */
    lateinit var wifiHotspotManager: WifiHotspotManager

    fun getServerUrl(): String {
        val ip = wifiHotspotManager.getLocalIpAddress()
        return "http://$ip:$PORT"
    }
    
    /**
     * 简单的HTTP服务器实现
     */
    private inner class SimpleHttpServer(
        port: Int,
        private val accessCounter: AtomicInteger
    ) : NanoHTTPD(port) {
        
        override fun serve(session: IHTTPSession): Response {
            try {
                Log.d(TAG, "请求详情: uri=${session.uri}, method=${session.method}, params=${session.parameters}")
                val uri = session.uri
                Log.d(TAG, "收到请求: $uri")
                
                when (uri) {
                    "/" -> {
                        // 主页
                        val newCount = accessCounter.incrementAndGet()
                        // UI回调切主线程（Kotlin协程）
                        GlobalScope.launch(Dispatchers.Main) {
                            onAccessCallback?.invoke(newCount)
                        }
                        val html = """
                            <!DOCTYPE html>
                            <html>
                            <head>
                                <title>WiFi热点访问</title>
                                <meta charset="utf-8">
                                <meta name="viewport" content="width=device-width, initial-scale=1">
                                <style>
                                    body { font-family: Arial, sans-serif; text-align: center; padding: 20px; }
                                    .container { max-width: 600px; margin: 0 auto; }
                                    .success { color: #4CAF50; font-size: 24px; margin: 20px 0; }
                                    .info { background: #f0f0f0; padding: 15px; border-radius: 5px; margin: 20px 0; }
                                </style>
                            </head>
                            <body>
                                <div class="container">
                                    <h1>WiFi热点访问成功</h1>
                                    <div class="success">✅ 访问成功</div>
                                    <div class="info">
                                        <p>欢迎连接到WiFi热点！</p>
                                        <p>当前访问次数: ${accessCounter.get()}</p>
                                    </div>
                                    <p>感谢您的访问！</p>
                                </div>
                            </body>
                            </html>
                        """.trimIndent()
                        
                        return newFixedLengthResponse(Response.Status.OK, "text/html; charset=utf-8", html)
                    }
                    
                    "/api/access" -> {
                        // API接口
                        val newCount = accessCounter.incrementAndGet()
                        onAccessCallback?.invoke(newCount)
                        val json = """
                            {
                                "status": "success",
                                "message": "访问成功",
                                "accessCount": ${accessCounter.get()},
                                "timestamp": ${System.currentTimeMillis()}
                            }
                        """.trimIndent()
                        
                        return newFixedLengthResponse(Response.Status.OK, "application/json", json)
                    }
                    
                    "/api/status" -> {
                        // 状态接口
                        val json = """
                            {
                                "serverRunning": true,
                                "accessCount": ${accessCounter.get()},
                                "port": $PORT
                            }
                        """.trimIndent()
                        
                        return newFixedLengthResponse(Response.Status.OK, "application/json", json)
                    }
                    
                    else -> {
                        // 404页面
                        val html = """
                            <!DOCTYPE html>
                            <html>
                            <head>
                                <title>页面未找到</title>
                                <meta charset="utf-8">
                            </head>
                            <body>
                                <h1>404 - 页面未找到</h1>
                                <p>抱歉，您访问的页面不存在。</p>
                                <p><a href="/">返回首页</a></p>
                            </body>
                            </html>
                        """.trimIndent()
                        
                        return newFixedLengthResponse(Response.Status.NOT_FOUND, "text/html; charset=utf-8", html)
                    }
                }
            } catch (e: Exception) {
                Log.e(TAG, "处理HTTP请求失败", e)
                val stackTrace = e.stackTraceToString()
                return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, "text/plain", "服务器内部错误: ${e.message}\n$stackTrace")
            }
        }
    }
}
